<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/14
 * Time: 13:20
 */
namespace QinNiuDeveloper\api;
require_once __DIR__ . '/../autoload.php';

// 引入鉴权类
use Qiniu\Auth;

// 引入上传类
use Qiniu\Storage\UploadManager;


use Qiniu\Config;


use Qiniu\Storage\BucketManager;


class Qin{

    private $accessKey;

    private $secretKey;

    private $bucket;

    private $filePath;

    private $key;
    /**
     * Qin constructor.
     */
    public function __construct($config)
    {

        $this->accessKey = $config["accessKey"];
        $this->secretKey = $config["secretKey"];
        $this->bucket    = $config["bucket"];
        $this->filePath  = $config["filePath"];
        $this->key       = $config["key"];


    }


    /**
     * qinNiu上传图片
     * @throws \Exception
     */
    public function uploadsImage(){

        $auth = new Auth($this->accessKey, $this->secretKey);

        // 生成上传 Token
        $token = $auth->uploadToken($this->bucket);

        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $this->key, $this->filePath);

        if ($err !== null) {
            return json_encode(["status"=>0,"data"=>$err]);
        } else {
            //var_dump($ret);
            return json_encode(["status"=>1,"data"=>$ret]);
        }

    }

    /**
     * 删除图片
     * @return string
     */
    public function delImage(){

        $auth = new Auth($this->accessKey, $this->secretKey);
        $config = new Config();
        $bucketManager = new BucketManager($auth, $config);
        $err = $bucketManager->delete($this->bucket, $this->key);
        if ($err) {
            //print_r($err);
            return json_encode(["status"=>0,"data"=>$err]);
        }
        return json_encode(["status"=>1]);
    }




}